package com.kyh.service.sys.impl;

import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.alibaba.fastjson.JSONObject;
import com.kyh.enume.sys.ColEnum;
import com.kyh.enume.sys.MenuEnum;
import com.kyh.mapper.CommonMapper;
import com.kyh.properties.AppProps;
import com.kyh.service.sys.CommonService;
import com.kyh.sys.entity.Button;
import com.kyh.sys.entity.Col;
import com.kyh.sys.entity.Columns;
import com.kyh.sys.entity.Menu;
import com.kyh.sys.mapper.SysCommonMapper;
import com.kyh.util.CheckUtil;
import com.kyh.util.StringBoUtil;
import com.kyh.util.StringUtils;
import com.kyh.util.sys.ColUtil;

@Service("commonService")
public class CommonServiceImpl implements CommonService {
	
	@Autowired
	private CommonMapper commonMapper;
	
	@Autowired
	private SysCommonMapper sysCommonMapper;

	@Override
	public String add(Model model, HttpServletRequest request, Long menuId) {
    	
    	if (menuId == null) {
    		model.addAttribute("errormsg", "菜单ID不能为空");
			return "common/error";
		}

    	Menu menu = new Menu().setMenuId(menuId).queryFirst();
		
		// 获取字段数组
		List<Col> listCol = new Col().setMenuId(menuId).setOrderby("A.col_sort_no asc").queryList();

		String tableAllName = menu.getMenuTable();
		
		String inputsAdd = ColUtil.getInputsAdd(listCol, sysCommonMapper, commonMapper, null);
		
		JSONObject menuJO = menu.modelTable();
		
		String tableReplaceName = "";
		if (tableAllName.startsWith("ta_")) {
			tableReplaceName = tableAllName.substring(3);
		} else if (tableAllName.startsWith("sys_")) {
			tableReplaceName = tableAllName.substring(4);
		} else if (tableAllName.startsWith("t_")) {
			tableReplaceName = tableAllName.substring(2);
		} else {
			tableReplaceName = tableAllName;
		}
		String str = StringBoUtil.lowerFirst(StringBoUtil.replaceUnderLineAndUpperCase(tableReplaceName));
		menuJO.put("menuTable", str);
		
		model.addAttribute("menu", menuJO);
		
		model.addAttribute("inputsAdd", inputsAdd);

        return "add";
	}

	@Override
	public String edit(
			Model model,
    		HttpServletRequest request,
    		Long menuId,
    		Long valId,
    		Integer pageType) {
    	
    	if (menuId == null) {
    		model.addAttribute("errormsg", "菜单ID不能为空");
			return "common/error";
		}
    	
    	if (valId == null) {
    		model.addAttribute("errormsg", "ID不能为空");
			return "common/error";
		}
    	
    	// 页面类型处理
    	if (pageType == null) {
    		pageType = 1;
		}
    	model.addAttribute("pageType", pageType);

    	Menu menu = new Menu().setMenuId(menuId).queryFirst();
		String tableAllName = menu.getMenuTable();

		String tableSchema = AppProps.get("jdbc.databaseName");
		if (tableAllName.startsWith("sys_")) {
			tableSchema = AppProps.get("admin.jdbc.databaseName");
		}
		
		List<Columns> listColumns = new Columns().setTableSchema(tableSchema).setTableName(tableAllName).queryList();

    	String menuPkName = new Columns().setTableSchema(tableSchema).setTableName(tableAllName).setColumnKey("PRI").queryFirst().getColumnName();
		Map<String, Object> entity = getEntity(listColumns, tableAllName, menuPkName, valId);
		
		// 获取字段数组
		List<Col> listCol = new Col().setMenuId(menuId).setOrderby("A.col_sort_no asc").queryList();
		String inputsEdit = ColUtil.getInputsEdit(listCol, menuPkName, sysCommonMapper, commonMapper, entity);
		
		JSONObject menuJO = menu.modelTable();
		
		String tableReplaceName = "";
		if (tableAllName.startsWith("ta_")) {
			tableReplaceName = tableAllName.substring(3);
		} else if (tableAllName.startsWith("sys_")) {
			tableReplaceName = tableAllName.substring(4);
		} else if (tableAllName.startsWith("t_")) {
			tableReplaceName = tableAllName.substring(2);
		} else {
			tableReplaceName = tableAllName;
		}
		String menuTable = StringBoUtil.lowerFirst(StringBoUtil.replaceUnderLineAndUpperCase(tableReplaceName));
		menuJO.put("menuTable", menuTable);
		
		model.addAttribute("menu", menuJO);
		
		model.addAttribute("inputsEdit", inputsEdit);

        return "edit";
	}

	@Override
	public String inter(Model model,
    		HttpServletRequest request,
    		Long menuId,
    		Integer menuTypeTemplet,
    		Long roleId) {

    	String param = "";
		Enumeration<String> reqNames = request.getParameterNames();
		for (; reqNames.hasMoreElements();) {
			String name = reqNames.nextElement();
			if (!"menuId".equals(name)
					&& !"menuTypeTemplet".equals(name)) {
				param = param + name + ": '" + request.getParameter(name) + "',";
			}
		}

    	Menu menu = new Menu().setMenuId(menuId).queryFirst();
    	
    	// 菜单是否显示统计
    	StringBuffer buttonCount = new StringBuffer("");
    	if (menu.getShowCount() == MenuEnum.ShowCount.YES.value) {
    		buttonCount.append("<input name=\"isCount\" type=\"checkbox\" value=\"false\">")
    		.append("<script>")
    		.append("$(function () {")
    		.append("$('[name=\"isCount\"]').bootstrapSwitch({")
    		.append("onText:'统计',")
    		.append("offText:'不统计',")
    		.append("onColor:'success',")
    		.append("offColor:'warning',")
    		.append("onSwitchChange:function(event,state){")
    		.append("if(state==true){")
    		.append("$(this).val('true');")
    		.append("} else {")
    		.append("$(this).val('false');")
    		.append("}")
    		.append("}")
    		.append("});")
    		.append("});")
    		.append("</script>");
		}
    	model.addAttribute("buttonCount", buttonCount.toString());

    	Button condButton = new Button().setMenuId(menuId).setOrderby("A.button_id asc");
    	if (roleId != null) {
			condButton.where("A.button_id in (select button_id from sys_role_button where role_id = " + roleId + " and status = 1)");
		}
    	
    	List<Button> listButton = condButton.queryList();

		model.addAttribute("listButton", listButton);
		StringBuffer buttonScripts = new StringBuffer("");
		for(Button button : listButton) {
			String buttonScriptsStr = button.getScripts();
			if (CheckUtil.notNull(buttonScriptsStr)) {
				buttonScripts.append(buttonScriptsStr).append("\n");
			}
		}
		model.addAttribute("buttonScripts", buttonScripts.toString());

		model.addAttribute("listButton", listButton);
		
		// 获取字段数组
		List<Col> listCol = new Col().setMenuId(menuId).setOrderby("A.col_sort_no asc").queryList();

		String tableAllName = menu.getMenuTable();
		String tableSchema = AppProps.get("jdbc.databaseName");
		if (tableAllName.startsWith("sys_")) {
			tableSchema = AppProps.get("admin.jdbc.databaseName");
		}
		
		Columns columnsClass = new Columns().setTableSchema(tableSchema).setTableName(tableAllName).setColumnKey("PRI").queryFirst();
		String menuPkName = columnsClass.getColumnName();
		String columns = ColUtil.getColumns(listCol, menu, sysCommonMapper, commonMapper);
		String inputsAdd = ColUtil.getInputsAdd(listCol, sysCommonMapper, commonMapper, null);
		String inputsSearch = ColUtil.getInputsSearch(listCol, sysCommonMapper, commonMapper);
		String jsParamsInit = ColUtil.getJsParamsInit(menu, menuPkName, listCol);
		
		JSONObject menuJO = menu.modelTable();
		menuJO.put("menuPkName", StringBoUtil.lowerFirst(StringUtils.replaceUnderlineAndfirstToUpper(menuPkName)));
		
		String tableReplaceName = "";
		if (tableAllName.startsWith("ta_")) {
			tableReplaceName = tableAllName.substring(3);
		} else if (tableAllName.startsWith("sys_")) {
			tableReplaceName = tableAllName.substring(4);
		} else if (tableAllName.startsWith("t_")) {
			tableReplaceName = tableAllName.substring(2);
		} else {
			tableReplaceName = tableAllName;
		}
		menuJO.put("menuTable", StringBoUtil.lowerFirst(StringBoUtil.replaceUnderLineAndUpperCase(tableReplaceName)));
		
		model.addAttribute("menu", menuJO);
		
		model.addAttribute("columns", columns);
		model.addAttribute("inputsAdd", inputsAdd);
		model.addAttribute("inputsSearch", inputsSearch);
		model.addAttribute("jsParamsInit", param + jsParamsInit);
		
		// 自定义链接地址
		if (menuTypeTemplet == null) {
			menuTypeTemplet = menu.getMenuTypeTemplet();
		}
		if (menuTypeTemplet == MenuEnum.TypeTemplet.LIST_NORMAL.value) {
	        return "templetList";
		} else if (menuTypeTemplet == MenuEnum.TypeTemplet.TREE_WITH_LIST.value) {
	        return "templetTreeList";
		} else if (menuTypeTemplet == MenuEnum.TypeTemplet.TREE_WITH_CHECKBOX.value) {
	        return "templetTreeBox";
		} else if (menuTypeTemplet == MenuEnum.TypeTemplet.UP_AND_DOWN.value) {
	        return "templetListUpDown";
		} else if (menuTypeTemplet == MenuEnum.TypeTemplet.DIY.value) {
	        return menu.getMenuDiy();
		} else {
	        return "templetList";
		}
	}

	@Override
	public String selector(Model model, HttpServletRequest request, Long colId, String objId) {
    	Col col = new Col().setColId(colId).queryFirst();
    	if (col.getColType() != ColEnum.ColType.SELECTOR_MODAL.value) {
    		model.addAttribute("errormsg", "非弹出选择框类型无法加载数据");
			return "common/error";
		}
    	
    	if (objId == null || objId.length() == 0) {
    		model.addAttribute("errormsg", "ID不能为空");
			return "common/error";
		}
    	
		model.addAttribute("urlSearch", col.getUrlSearch());
		model.addAttribute("field", col.getFieldName());
		model.addAttribute("objId", objId);
		
        return "templetListSelector";
	}

	@Override
	public String importExcel(
			Model model,
			HttpServletRequest request,
    		Long menuId) {

    	Menu menu = new Menu().setMenuId(menuId).queryFirst();
		JSONObject menuJO = menu.modelTable();
		String tableAllName = menu.getMenuTable();
		String tableReplaceName = "";
		if (tableAllName.startsWith("ta_")) {
			tableReplaceName = tableAllName.substring(3);
		} else if (tableAllName.startsWith("sys_")) {
			tableReplaceName = tableAllName.substring(4);
		} else if (tableAllName.startsWith("t_")) {
			tableReplaceName = tableAllName.substring(2);
		} else {
			tableReplaceName = tableAllName;
		}
		String menuTable = StringBoUtil.lowerFirst(StringBoUtil.replaceUnderLineAndUpperCase(tableReplaceName));
		menuJO.put("menuTable", menuTable);
		model.addAttribute("menu", menuJO);

		String idFile = "id_file_import_excel";
		String idInput = "id_input_import_excel";

		StringBuffer sb = new StringBuffer("");
		sb
		.append("<div class='form-group col-md-12'>")
		.append("	<label class='col-sm-3 control-label'>要导入的文件</label>")
		.append("	<div class='col-sm-9'>")
		.append("		<div class='file-loading'>")
		.append("			<input class='file' type='file' data-theme='fas' id='" + idFile + "'>")
		.append("		</div>")
		.append("		<input type='hidden' name='fileUrl' value='' id='" + idInput + "' />")
		.append("	</div>")
		.append("</div>");
		
		sb.append("<script>")
			.append("$(function () {")
				.append("$BO.initExcelInput($('#" + idFile + "'), $('#" + idInput + "'), '');")
			.append("});")
		.append("</script>");
		
		model.addAttribute("inputsImportExcel", sb.toString());
		
        return "importExcel";
	}
    
    private String getSqlField(List<Columns> listColumns) {
    	
    	StringBuffer sb = new StringBuffer("select ");
    	for (Columns columns : listColumns) {
    		String columnName = columns.getColumnName();
    		if (columnName.equals("key")) {
    			columnName = "`" + columnName + "`";
			}
    		sb.append(columnName + " AS " + StringUtils.replaceUnderlineAndfirstToUpper(columnName) + ",");
    	}
    	
    	String sbStr = sb.toString();
    	return sbStr.substring(0, sbStr.length() - 1) + " ";
    }
    
    private Map<String, Object> getEntity(List<Columns> listColumns, String tableAllName, String menuPkName, Long valId) {
		
		String sqlStr = getSqlField(listColumns) + "from " + tableAllName + " where " + menuPkName + "=" + valId.longValue();
		
    	List<Map<String, Object>> listMap;
    	if (tableAllName.startsWith("sys_")) {
    		listMap = sysCommonMapper.searchMap(sqlStr);
		} else {
    		listMap = commonMapper.searchMap(sqlStr);
		}
    	
    	if (listMap != null && listMap.size() > 0) {
        	return listMap.get(0);
		} else {
			return null;
		}
    }
}
